package com.weixing.mall.pay.channel.wx.payment;

import com.weixing.mall.pay.PayParam;
import com.weixing.mall.pay.PayResult;
import com.weixing.mall.pay.channel.wx.AbstractWxPay;
import com.weixing.mall.pay.channel.wx.WxPaySet;
import com.weixing.mall.pay.channel.wx.WxTradeTypeEnum;
import com.weixing.mall.pay.channel.wx.sdk.WXPay;
import com.weixing.mall.pay.channel.wx.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxPayXCX
 * @Description 微信小程序支付
 * @Author Small
 * @Date 2019/11/28 9:52
 * @Version 1.0
 **/
@Slf4j
public class WxPayXCX extends AbstractWxPay {
    private static WxTradeTypeEnum tradeType = WxTradeTypeEnum.XCX;

    public WxPayXCX(WxPaySet wxPaySet) {
        super(wxPaySet, tradeType);
    }

    /**
     * 方法描述: 支付
     * @Author Small
     * @param payParam
     * @Date 2019/11/29 10:02
     * @return com.weixing.mall.pay.PayResult
     */
    @Override
    public PayResult pay(PayParam payParam) {
        // 发起微信付款
        String outTransNo = payParam.getOutTransNo();
        log.info("WxPay::小程序=>订单{} 支付请求到达", outTransNo);
        HashMap<String, String> data = wapperRequestData(payParam, WxTradeTypeEnum.XCX.getValue());
        try {
            WXPay wxPay = initWxPay();
            Map<String, String> r = wxPay.unifiedOrder(data);
            log.info("WxPay::小程序=>订单{} 下单返回报文:{}", outTransNo, r);
            Map<String, String> resultMap = parseResponse(r);
            String resultCode = resultMap.get(RESULT_CODE);
            String resultMsg = resultMap.get(RESULT_MSG);
            if (SUCCESS.equals(resultCode)) {
                log.info("WxPay::小程序=>订单{} 下单成功", outTransNo);
                String prepayId = r.get("prepay_id");
                String appid = r.get("appid");
                Map<String, String> map = new HashMap<>();
                map.put("appId", appid);
                map.put("timeStamp", WXPayUtil.getCurrentTimestamp() + "");
                map.put("nonceStr", WXPayUtil.generateNonceStr());
                map.put("signType", "MD5");
                map.put("package", "prepay_id=" + prepayId);
                map.put("paySign", wxPay.generateSignature(map));
                map.put("orderNo", outTransNo);
                return PayResult.success(map);
            } else if (FAIL.equals(r.get(RESULT_CODE))) {
                log.info("WxPay::小程序=>订单{} 下单失败,错误代码{},错误原因{}", outTransNo, resultCode, resultMsg);
                return PayResult.fail(resultCode, resultMsg);
            }
        } catch (Exception e) {
            log.warn("WxPay::小程序=>订单{} 下单时发生异常", outTransNo, e);
        }
        return PayResult.unknowException();
    }

    @Override
    public boolean needOpenId() {
        return true;
    }
}